package com.fingard.dsp.bank.directbank.tzb01;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.MFSHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import static com.fingard.text.StringHelper.trimEndFileSp;

/**
 * Created by F on 2019/01/04.
 * 今日明细，历史明细
 */
public class TZB01Transaction extends TZB01Base implements ITransaction{
    /**
     * 历史明细
     * @param p_req7516
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception{
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        retAtsTrans.writeStart();
        String tmpRespCode = "";
        String tmpRespInfo ="";
        try{
            //起始日期
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            //结束日期
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while(tmpIntDateFrom<=tmpIntDateTo && StringHelper.isNullOrEmpty(tmpRespCode)){
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //当是跨月查询时，先查询起始日期到月末日期记录，再查询月末后一天日期到结束日期记录
                if(DateHelper.compareMonth(tmpCalendarFrom,tmpCalendarTo)==-1){
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH,tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                }else{
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                //拼接报文
                //非公有参数
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                //拼接请求报文头
                TZB01Header header=new TZB01Header();
                header.tr_code="200110";//交易码
                header.req_no=p_req7516.reqHeader.reqSeqID;
                writeCommonHeader(xmlTextWriter,header);
                xmlTextWriter.writeEndElement();
                //拼接请求报文体
                xmlTextWriter.writeStartElement("body");
                xmlTextWriter.writeElementString("acno",p_req7516.actNum);//帐号
                xmlTextWriter.writeElementString("cur_code",convertCurToBank(p_req7516.actCur));//币种
                xmlTextWriter.writeElementString("start_date",Format.Date8Format.format(tmpCalendarFrom.getTime()));//开始时间
                xmlTextWriter.writeElementString("end_date",Format.Date8Format.format(tmpClndrStepTo.getTime()));//结束时间
                xmlTextWriter.writeEndDocument();
                //拼接报文头
                int length=xmlTextWriter.toXmlString().getBytes(getCharset()).length+2;
                String head=String.format("%-10s",length+"")+"00";
                //发送请求报文
                String[] resutlt = sendToBank(head+xmlTextWriter.toXmlString());
                //处理响应报文
                if(resutlt[0].length()==0){
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(resutlt[1].substring(resutlt[1].indexOf("<ap>")), tmpSbMsg);
                    if(tmpBkReader!=null) {
                        String succFlag= tmpBkReader.getFirstText("/ap/head/succ_flag");
                        String respCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                        String respInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                        if ("0".equals(succFlag) && "0000".equals(respCode)) {//交易成功
                            String totalNum=tmpBkReader.getFirstText("/ap/body/record_num");//总数
                            String valueNum=tmpBkReader.getFirstText("/ap/body/field_num");//字段数
                            String serial_recode = "";
                            if ("1".equals(tmpBkReader.getFirstText("/ap/head/file_flag"))) {
                                String tmpBatchFileName = tmpBkReader.getFirstText("/ap/body/file_name");
                                String p_FileFullPath = getTempFileDirectory() + File.separator + Format.Time6Format.format(new Date());//下载到的本地路径
                                //等待文件缓冲
                                Thread.sleep(300000);
                                String saveType = this.getBankConfig().getValueAsString("saveType");
                                if(saveType!=null && saveType.equals("sftp")){
                                    SftpPortClient sftpPortClient = null;
                                    try {
                                        FtpSet ftpSet = bankFront.getFtpSet("statement");
                                        ftpSet.downDir = com.fingard.text.StringHelper.trimEnd(ftpSet.downDir, "/") + "/";
                                        WriteBankLogLn("SFTP下载地址" + ftpSet.serverIP + ":" + ftpSet.port);

                                        sftpPortClient = new SftpPortClient(ftpSet);
                                        sftpPortClient.connect();
                                        WriteBankLogLn("下载的路径为:"+ftpSet.downDir);
                                        FtpReceiver ftpReceiver = sftpPortClient.downloadFileByName("" ,p_FileFullPath,tmpBatchFileName);
                                        if(ftpReceiver.isCompleted){
                                            WriteBankLogLn("下载成功，下载路径为："+p_FileFullPath+"文件名为"+tmpBatchFileName);
                                        }else{

                                            WriteBankLogLn("下载失败，文件名为"+tmpBatchFileName);
                                        }
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                        WriteBankLogLn(ex);
                                    } finally {
                                        if (sftpPortClient != null) {
                                            sftpPortClient.disconnect();
                                        }
                                    }
                                    p_FileFullPath = p_FileFullPath + File.separator + tmpBatchFileName;
                                    serial_recode = FileHelper.readFileText(p_FileFullPath, getCharset());
                                }else {
                                    //下载共享目录批量查询文件
                                    String downloadFilePath = trimEndFileSp(bankFront.bankReceiptMainDir) + File.separator;//共享目录路径
                                    WriteBankLogLn("共享目录文件，位于：" + downloadFilePath);
                                    StringBuilder p_sb = new StringBuilder();
                                    if (SmbFileUtil.smbDownloadInChar(p_FileFullPath, downloadFilePath, tmpBatchFileName, p_sb) == 1) {
                                        WriteBankLogLn("文件下载成功，位于：" + p_FileFullPath);
                                        p_FileFullPath = p_FileFullPath + File.separator + tmpBatchFileName;
                                        serial_recode = FileHelper.readFileText(p_FileFullPath, getCharset());
                                    } else {
                                        retAtsTrans.writeRespCode("-1");
                                        retAtsTrans.writeRespInfo(p_sb.toString());
                                        retAtsTrans.writeEnd();
                                        return retAtsTrans;
                                    }
                                }
                            }else{
                                serial_recode=tmpBkReader.getFirstText("/ap/body/serial_record");//字段域
                            }
                            if(!"0".equals(totalNum) && !"0".equals(valueNum) && !StringHelper.isNullOrEmpty(serial_recode)){
                                //0、平台流水号（C20）|1、账号（C35）|2、货币码（C2）|3、交易日期（C8）|4、交易时间交易日期（C6）|5、主机流水号（C20）|6、交易行号(C12)|
                                //7、户名(C70)|8、对方账号(C35)|9、对方货币码(C2)|10、对方账号户名(C70)|11、对方账号开户行(C60)|12、对方行号(C12)|13、交易类别(C1)|14、钞汇标志(C1)|
                                //15、他行标志(C1)|16、同城异地标志(C1)|17、手续费(N16.2)|18、交易来源(C1)|19、发生额标志(C1)|20、被冲销流水号(C12)|21、原交易日期(C8)|22、现转标志(C1)|
                                //23、借贷标志(C1)|24、交易金额(N16.2)|25、余额(N16.2)|26、上笔余额(N16.2)|27、冻结金额(N16.2)|28、凭证种类(C20)|29、凭证批次号(C20)|30、凭证号码(C20)|
                                //31、交易码(C6)|32、柜员号(C10)|33、传票号(C20)|34、摘要(C30)|35、附言(C60)|36、交易时间戳|37、备注字段一(C60)|38、备注字段二(C60)|39、交易行名（C60）|
                                //40、行号（C12）|41、打印次数（N10）|42、支出金额(N16.2)|43、收入金额（N16.2）|
                                StringBuilder tmpSbLog = new StringBuilder();
                                ArrayList<String[]> tmpArrayList = MFSHelper.getTextArray(serial_recode, "|", Integer.parseInt(valueNum), Integer.parseInt(totalNum) + 1, tmpSbLog);
                                if (tmpSbLog.length() == 0) {
                                    for (int i = 1; i < tmpArrayList.size(); i++) {
                                        {
                                            String[] tmpEachArr = tmpArrayList.get(i);
                                            RetAtsTransDetail detail = new RetAtsTransDetail();
                                            detail.actArea = p_req7516.actArea;//账户区域
                                            detail.actNum = p_req7516.actNum;//银行账号
                                            detail.recAccNum = tmpEachArr[8].trim();//收方银行账号
                                            detail.recAccName = tmpEachArr[10].trim();//收方账户名称
                                            detail.recAccBank = tmpEachArr[11].trim();//收方银行
                                            detail.tranDate = DateHelper.convertD8toD10(tmpEachArr[3].trim());//交易日期
                                            String time=tmpEachArr[3].trim();//交易时间
                                            if(time.length()==6){
                                                detail.tranTime = detail.tranDate + time.substring(0,2)+":"+time.substring(3,4)+":"+time.substring(5,6);//交易时间
                                            }else {
                                                detail.tranTime = detail.tranDate + "00:00:00";//交易时间
                                            }
                                            detail.valueDate = detail.tranDate;//起息日，银行没有返回就用tranDate交易日期
                                            detail.tranAmt = tmpEachArr[24].trim();//交易金额
                                            String cdFlag= tmpEachArr[23].trim();//借贷标识
                                            if ("D".equals(cdFlag)) {
                                                if(detail.tranAmt.indexOf("-")>=0) {
                                                    detail.cdFlag = "2";
                                                    detail.tranAmt = detail.tranAmt.substring(1);
                                                }else{
                                                    detail.cdFlag = "1";
                                                }
                                            } else if("C".equals(cdFlag)){
                                                if(detail.tranAmt.indexOf("-")>=0){
                                                    detail.cdFlag = "1";
                                                    detail.tranAmt = detail.tranAmt.substring(1);
                                                }else{
                                                    detail.cdFlag = "2";
                                                }
                                            }else {
                                                tmpRespCode ="-1";
                                                tmpRespInfo = "返回借贷标识异常";
                                                break;
                                            }
                                            detail.accBal = tmpEachArr[25].trim();//账户余额
                                            String note = tmpEachArr[34].trim();
                                            detail.usage = note;//摘要
                                            detail.abstr = pickupAbstr(note);//对账码
                                            detail.cur = convertCurToATS(tmpEachArr[9].trim());//币种
                                            detail.originator=tmpEachArr[32].trim();//柜员号
                                            detail.askNumber = tmpEachArr[30].trim();//流水号
                                            retAtsTrans.writeRetDetail(detail);
                                        }
                                    }
                                } else {
                                    tmpRespCode ="-1";
                                    tmpRespInfo = tmpSbLog.toString();
                                }
                            }else {
                                tmpRespCode ="0";
                                tmpRespInfo = "该时间段的总明细条数为0";
                            }
                        }else {//查询异常
                            tmpRespCode = "-1";
                            tmpRespInfo = respInfo;
                            break;
                        }
                    }else{
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                }else{
                    tmpRespCode = "-1";
                    tmpRespInfo = resutlt[1];
                    break;
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        }catch (Exception ex){
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
            WriteBankLogLn("查询明细异常:"+ex);
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        }else if(retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespInfo("交易为空");
            retAtsTrans.writeRespCode("0");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }

    /**
     * 今日明细
     * @param p_req7515
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception{
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actArea = p_req7515.actArea;
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        String date = Format.Date8Format.format(new Date());
        p_req7516.dateFrom = date;
        p_req7516.dateTo = date;
        return d_7516_HisTrans(p_req7516);
    }
}
